from pypump.models.image import Image
import threading


class FeedThread(threading.Thread):

    def __init__(self, queue, feed, starting_index, batch_size, **kwargs):
        threading.Thread.__init__(self)
        self.queue = queue
        self.feed = feed
        self.index = starting_index
        self.batch_size = batch_size

    def run(self):
        self.fetch_feed_content()

    # NOTE: some mediagoblin instances cant do [non-zero-num:num] splicing
    def fetch_feed_content(self):
        inbox_empty = True
        current_index = self.index
        print ('current index and batch size: {0}, {1}'.format(
            self.index, self.batch_size))
        try:
            for activity in self.feed[self.index:(self.index + self.batch_size)]:
                inbox_empty = False
                if isinstance(activity.obj, Image):
                    if not self.is_graveyard_activity(activity):
                        self.queue.put(str(current_index), activity)
                        current_index += 1
            # implies we didn't get any hits:
            if current_index == self.index and inbox_empty is False:
                self.queue.put('none', None)
            elif inbox_empty is True:
                self.queue.put('error', None)
            else:
                self.queue.put('done', None)
        except Exception, e:
            print (e)
            self.queue.put('error', None)
        self.is_running = False

    def is_graveyard_activity(self, activity):
        try:
            activity.obj.comments
        except KeyError:
            return True
        return False
